//
//  Set3Des.m
//  xhtios1.0
//
//  Created by hlt on 15/7/10.
//  Copyright (c) 2015年 hlt. All rights reserved.
//

//
//  Set3DES.m
//  xhtios1.0
//
//  Created by hlt on 15/7/7.
//  Copyright (c) 2015年 hlt. All rights reserved.
//

#import "Set3Des.h"

#import "GTMBase64.h"


@implementation Set3Des




+(NSString*)TripleDES:(NSString*)plainText deskey:(NSString *)deskey encryptOrDecrypt:(CCOperation)encryptOrDecrypt
{
    
    const void *vplainText;
    size_t plainTextBufferSize;
    
    if (encryptOrDecrypt == kCCDecrypt)//解密
    {
        NSData *EncryptData = [GTMBase64 decodeData:[plainText dataUsingEncoding:NSUTF8StringEncoding]];
        plainTextBufferSize = [EncryptData length];
        vplainText = [EncryptData bytes];
    }
    else //加密
    {
        //首先转换为nsdata类型
        NSData* data = [plainText dataUsingEncoding:NSUTF8StringEncoding];
        plainTextBufferSize = [data length];
        //转换为bytes类型
        vplainText = (const void *)[data bytes];
    }
    
    CCCryptorStatus ccStatus;
    uint8_t *bufferPtr = NULL;
    size_t bufferPtrSize = 0;
    size_t movedBytes = 0;
    //得到数据的长度（添加3des偏移之后的）
    bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
    //申请内存空间
    bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
    //将内存空间原来的值清零
    memset((void *)bufferPtr, 0x0, bufferPtrSize);
    // memset((void *) iv, 0x0, (size_t) sizeof(iv));
    
    
    //定义一个加密的key,不同的可以得到的结果也不一样
    const void *vkey = (const void *)[deskey UTF8String];
    // NSString *initVec = @"init Vec";
    //    const void *vinitVec = (const void *) [initVec UTF8String];
    //      Byte iv[] = {0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF};
    
    
    
    
    ccStatus = CCCrypt(encryptOrDecrypt,
                       kCCAlgorithm3DES,    //kChosenDigestLength
                       kCCOptionPKCS7Padding|kCCOptionECBMode,  //如果配置就是ecb不配置就是cbc
                       vkey,
                       kCCKeySize3DES,
                       nil,   //这个是偏移量，这里传入密钥
                       vplainText,
                       plainTextBufferSize,
                       (void *)bufferPtr,
                       bufferPtrSize,
                       &movedBytes);
    //if (ccStatus == kCCSuccess) NSLog(@"SUCCESS");
    
    
    NSString *result;
    
    if (encryptOrDecrypt == kCCDecrypt)
    {
        result = [[NSString alloc] initWithData:[NSData dataWithBytes:(const void *)bufferPtr
                                                               length:(NSUInteger)movedBytes]
                                       encoding:NSUTF8StringEncoding]
        ;
    }
    else
    {
        NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
        result = [GTMBase64 stringByEncodingData:myData];
    }
    
    return result;
}




@end
